package com.example.chat.api;


import com.example.chat.component.OnlineUserManager;
import com.example.chat.model.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.List;

@Component
public class WebSocketAPI extends TextWebSocketHandler {

    @Autowired
    private MessageSessionMapper messageSessionMapper;
    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private OnlineUserManager onlineUserManager;

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("[WebSocketAPI] 连接成功！");

        User user = (User)session.getAttributes().get("user");
        if (user == null) {
            return;
        }

        onlineUserManager.online(user.getUserId(), session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println("[WebSocketAPI] 收到消息！ " + message.toString());

        User user = (User)session.getAttributes().get("user");
        if (user == null) {
            System.out.println("[WebSocketAPI] user == null，用户未登录");
            return;
        }

        // 用 objectMapper 来进行 Java对象 和 Json格式的字符串 之间的转化
        // getPayload()方法：从消息对象中获取实际的有效负载（payload）即消息数据部分
        MessageRequest req = objectMapper.readValue(message.getPayload(), MessageRequest.class);

        // 判断请求类型是否符合
        if (req.getType().equals("message")) {
            transferMessage(user, req);
        } else {
            System.out.println("[WebSocketAPI] req.type 有误！" + message.getPayload());
        }
    }

    private void transferMessage(User fromUser, MessageRequest req) throws IOException {

        MessageResponse resp = new MessageResponse();
        resp.setType("message");
        resp.setFromId(fromUser.getUserId());
        resp.setFromName(fromUser.getUsername());
        resp.setSessionId(req.getSessionId());
        resp.setContent(req.getContent());

        // 将响应数据从 Java 对象转化为 Json 格式的字符串
        String respJson = objectMapper.writeValueAsString(resp);
        System.out.println("[transferMessage] respJson: " + respJson);

        // 通过 sessionId 拿到指定会话中 所有的用户（除了当前用户）
        List<Friend> friends =
                messageSessionMapper.getFriendsBySessionId(req.getSessionId(), fromUser.getUserId());

        // 构造一个自己，加入 friends 中，一起作为准备返回消息的目标用户
        Friend myself = new Friend();
        myself.setFriendId(fromUser.getUserId());
        myself.setFriendName(fromUser.getUsername());
        friends.add(myself);

        for (Friend friend : friends) {

            // 从 在线用户管理器 中获得准备返回消息的目标用户的会话
            WebSocketSession webSocketSession = onlineUserManager.getSession(friend.getFriendId());
            if (webSocketSession == null) {
                // 目标用户不在线，结束当前循环，直接在后续进行消息插入数据库即可
                continue;
            }

            // 目标用户在线
            // 用 respJson字符串 构造出 一个消息对象 利用 webSocketSession 发送到前端
            webSocketSession.sendMessage(new TextMessage(respJson));
        }

        // 消息存入数据库
        Message message = new Message();
        message.setFromId(fromUser.getUserId());
        message.setSessionId(req.getSessionId());
        message.setContent(req.getContent());

        messageMapper.add(message);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        System.out.println("[WebSocketAPI] 连接成功！ " + status.toString());

        User user = (User)session.getAttributes().get("user");
        if (user == null) {
            return;
        }

        onlineUserManager.offline(user.getUserId(), session);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        System.out.println("[WebSocketAPI] 连接成功！ " + exception.toString());

        User user = (User)session.getAttributes().get("user");
        if (user == null) {
            return;
        }

        onlineUserManager.offline(user.getUserId(), session);
    }
}
